package com.cloudminds.resttest.helper;

import com.cloudminds.resttest.api.CallManager;
import com.cloudminds.resttest.ice.AiasIceClient;
import com.cloudminds.resttest.ice.FrIceClient;
import com.cloudminds.resttest.push.PushClient;
import com.cloudminds.resttest.utils.Base64Utils;
import com.cloudminds.resttest.utils.FileUtils;
import com.cloudminds.resttest.vo.CallParams;
import org.json.JSONObject;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

public class NewFrHelper {

    private static NewFrHelper frHelper;
    private File[] facePaths;
    private ArrayList<byte[]> faceList = new ArrayList<>();
    private int AIAS_PIC_PER_SECTION_LEN = 60*1024;
    private static int index = 0;
    private Thread sendThread;
    private boolean faceRegEnable = false;
    private CallManager callManager;
    private FrIceClient frIceClient ;
    private        AiasIceClient     aiasIceClient;


    public NewFrHelper(String sid, FrIceClient frIceClient)
    {
        this.frIceClient = frIceClient;
        frHelper = this;
    }

   /* public NewFrHelper(String sid, PushClient pushClient)
    {
        this.pushClient = pushClient;
        frHelper = this;
    }*/



    private void loadFaces(String path){
        File file = new File(path+"/faces");
        //遍历faces文件夹下的图片
        if (file.exists()){
            facePaths = file.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    String s = name.toLowerCase();
                    if (s.startsWith("._")){
                        return false;
                    }
                    return s.endsWith(".png") || s.endsWith(".jpg");
                }
            });
        }

        faceList.clear();
        //读取人脸图片
        try {
            for (File item:facePaths) {
                byte[] audio = FileUtils.getContent(item);
                if (audio!=null && audio.length>0){
                    faceList.add(audio);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void startFr(String sid){
        if (faceList.size()==0){
            String path = new File("").getAbsolutePath();
            System.out.println("File path :"+path);
            loadFaces(path);
        }
        faceRegEnable = true;
        if (null!=faceList && faceList.size()>0){
            index = index<faceList.size()?index:0;
             sendOnePicture(sid,faceList.get(index),2,"faceStream",AIAS_PIC_PER_SECTION_LEN);
            index++;
        }

    }

    public void stopFr(){
        faceRegEnable = false;
        indexLastChangedTime = -1;
    }


    /**
     *
     * @param picBytes
     * @param picIndex  图片在数组中的index， 第一张0 最后一张2 中间张 1
     * @param cmdType
     */
    private JSONObject sendOnePicture(String sid,final byte[] picBytes, int picIndex, String cmdType, int secLen){
        JSONObject json =new JSONObject();
        try {
            System.out.println("--- SendPicture entry! cmd:"+cmdType);

            System.out.println("Pic size:"+ picBytes.length + " picIndex:"+picIndex);

            String picString  = Base64Utils.encodeToString(picBytes);
            System.out.println("Encoded pic string length:"+picString.length());

            long resLen = picString.length()%secLen;
            int blockNum = (int) (picString.length()/secLen) + (picString.length()%secLen>0?1:0);

            for (int i=0;i<blockNum;i++){
                //JSONObject json = new JSONObject();
                json.put("type",cmdType);
                json.put("seq", System.currentTimeMillis());
                json.put("sid", sid);
                if (picIndex>=0){
                    json.put("streamFlag",picIndex);
                }

                JSONObject dataJson = new JSONObject();
                int index = (int) (i*secLen);

                if (i == blockNum-1){

                    dataJson.put("flag",2);  //段尾
                    dataJson.put("image",picString.substring(index,picString.length()));

                } else if(i==0) {

                    dataJson.put("flag",0); //段首
                    dataJson.put("image",picString.substring(index,secLen));

                } else {

                    dataJson.put("flag",1); //段中
                    dataJson.put("image",picString.substring(index,index+secLen));
                }

                //System.out.println("send picture with StreamFlag:"+picIndex+" flag:"+dataJson.getString("flag") + " seq:"+json.getString("seq"));

                json.put("data",dataJson);

                /*if (pushClient != null){
                    String jsonString = json.toString();
                    pushClient.push2AiAs(jsonString);
                }*/
                if (frIceClient != null){
                    String jsonString = json.toString();
                    frIceClient.sendFace(jsonString);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    private long indexLastChangedTime = -1;


}
